package com.leyou.user.controller;

import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

/**
 * @author CHERRY
 * @date 2018-09-15-10:33
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据是否存在
     *
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data, @PathVariable(value = "type", required = false) Integer type) {

        Boolean res = userService.checkUserData(data, type);
        if (res == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok(res);
    }

    /**
     * 生成验证码且发送短信
     *
     * @return
     */
    @PostMapping("send")
    public ResponseEntity<Void> createCaptchaAndSendMessage(@RequestParam("phone") String phone) {


        Boolean boo = this.userService.createCaptchaAndSendMessage(phone);

        if (boo == false || !boo) {
            //400
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //204
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 注册用户
     *
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> registerUser(@Valid User user, @RequestParam("code") String code) {
        Boolean boo = this.userService.register(user, code);
        if (boo == null || !boo) {
            //400
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 登录用户
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("login")
    public ResponseEntity<User> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = this.userService.login(username, password);
        if (user == null) {
            //400
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(user);
    }

}
